package com.nine.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.nine.entity.Permission;
import com.nine.service.UsersService;
import com.nine.service.impl.UsersServiceImpl;

//自定义的realm
@Component
public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UsersService usersService;
	
	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return super.getName();
	}
	
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		System.out.println("==============认证=================");
		String username=(String) token.getPrincipal();
		//UsersService usersService=new UsersServiceImpl();
		String password = usersService.getPwdByUname(username);
		System.out.println("password"+password);
		SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(username, password, getName());
		
		return info;
	}
	
	
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		// TODO Auto-generated method stub
		String username=(String)principal.getPrimaryPrincipal();
		
		if(username==null) {
			return null;
		}
		List<Permission> permissions = usersService.getPermissionByUname(username);
			if(permissions==null||permissions.size()==0) {
			return null;
			}
			System.out.println("==============授权==============");
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
			for (Permission p : permissions) {
				if(p!=null) {
					if(p.getPercode()!=null) {
						info.addStringPermission(p.getPercode());
					}
					
				}
				
			}
		return info;
	}
	
	

}
